﻿using System;
using System.IO;
using System.Text;

namespace QFXProxy.Model
{
    public class FileConverter : IFileConverter
    {
        public string BankId { get; set; }
        public string SourceFile { get; set; }
        public string DestinationFile { get; set; }
        public Encoding Encoding { get; set; }

        /// <summary>
        /// Default constructor.
        /// </summary>
        public FileConverter()
        {
            BankId = "00015";
            Encoding = Encoding.GetEncoding("ISO-8859-1");
        }

        /// <summary>
        /// Convert file from source to destination.
        /// </summary>
        public void Convert()
        {
            // If destination file is not set, then set to a default filename
            // based on the source filename.
            if (string.IsNullOrEmpty(DestinationFile))
            {
                DestinationFile = SourceFile + ".qfx";
            }

            using (TextReader reader = new StreamReader(SourceFile, Encoding))
            using (TextWriter writer = new StreamWriter(DestinationFile, false, Encoding))
            {
                string line;
                while ((line = reader.ReadLine()) != null)
                {
                    line = ConvertLine(line);
                    if (!line.StartsWith("<INTU.BID>"))
                    {
                        writer.WriteLine(line);
                    }
                    if (line.StartsWith("<LANGUAGE>"))
                    {
                        writer.WriteLine("<INTU.BID>" + BankId);
                    }
                }
            }

        }

        /// <summary>
        /// Method to convert the format of the line. This method usually converts from a OFX 2.0 format (XML based) to a QFX (OFX 1.0 based - non XML).
        /// </summary>
        /// <param name="line">Line string to be cleaned up.</param>
        /// <returns>Returns the cleaned up line.</returns>
        private static string ConvertLine(string line)
        {
            line = line.Trim();

            if (!line.StartsWith("</"))
            {
                var parts = line.Split(new[] { "</" }, StringSplitOptions.None);
                return parts[0];
            }

            return line;
        }
    }
}